package fx.mine.active.component.translate;

import com.dtflys.forest.Forest;
import fx.mine.active.component.translate.api.TranslateAPI;
import io.github.palexdev.materialfx.controls.MFXTextField;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.layout.AnchorPane;
import javafx.scene.text.Text;
import lombok.extern.log4j.Log4j2;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

@Log4j2
public class TranslatePane extends AnchorPane {
    MFXTextField field = new MFXTextField();
    MFXTextField field2 = new MFXTextField();

    public TranslatePane(Double width, double height) {
        setPrefSize(width, height);

        AnchorPane transGroupControlBar = new AnchorPane();
        transGroupControlBar.setPrefHeight(50);

        AnchorPane.setRightAnchor(transGroupControlBar, 50.0);
        AnchorPane.setLeftAnchor(transGroupControlBar, 50.0);
        AnchorPane.setTopAnchor(transGroupControlBar, 50.0);

        transGroupControlBar.getStyleClass().add("gcbar");
        getChildren().add(transGroupControlBar);


        AnchorPane.setLeftAnchor(field, 50.0);
        AnchorPane.setTopAnchor(field, 100.0);
        field.setPrefWidth(450);
        field.setPromptText("输入需要翻译的中文");
        field.textProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                log.info(newValue);
                String translate = translate(newValue, true);
                field2.setText(translate);
            }
        });


        AnchorPane.setTopAnchor(field2, 100.0);
        AnchorPane.setRightAnchor(field2, 50.0);
        field2.setPrefWidth(450);
        field2.setPromptText("输入需要翻译的英文");
        field2.textProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                log.info(newValue);
                field.setText(translate(newValue, false));
            }
        });

        getChildren().add(field);
        getChildren().add(field2);

        getStyleClass().add("translatePane");
        getStylesheets().add(getClass().getResource("/css/translatePane.css").toExternalForm());
    }

    private static String translate(String zhCNText, boolean en2cn) {
        TranslateAPI client = Forest.client(TranslateAPI.class);
        String result;
        if (en2cn) {
            result = client.googleTranslate(zhCNText, "en", "zh-CN");
        } else {
            result = client.googleTranslate(zhCNText, "zh-CN", "en");
        }
        Document document = Jsoup.parse(result);
        Elements select = document.select("body > div.root-container > div.result-container");
        return select.get(0).childNode(0).outerHtml();
    }
}
